package com.mbyte.easy.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.Check;
import com.mbyte.easy.admin.entity.Draft;
import com.mbyte.easy.admin.entity.DraftLog;
import com.mbyte.easy.admin.entity.Group;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.*;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassNameDraftCheckLeaderController
 * @Description 稿件校对组长分配任务给校对人
 * @Author myr
 * @Date 2019/12/11 9:43
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/distribute/draftCheckLeader")
public class DraftCheckLeaderController extends BaseController {

    private String prefix = "admin/draft/draftCheckLeader/";

    @Autowired
    private IAllotService allotService;
    @Autowired
    private IDraftService draftService;
    @Autowired
    private IRelationService relationService;
    @Autowired
    private IPptService pptService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 稿件校对组长分配稿件首页
     * @Author myr
     * @param model
     * @param allot
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping
    public String draftCheckLeaderIndex(Model model,Draft allot,
                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace ,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {

        model.addAttribute("searchInfo", allot);
        model.addAttribute("pageInfo", new PageInfo(allotService.draftCheckLeaderIndex(allot,pageNo,pageSize,createTimeSpace)));
        model.addAttribute("draftTypes",draftService.setDraftType());//稿件类型回显
        model.addAttribute("draftCheckStatus",draftService.setDraftCheckStatus());//稿件审核状态回显
        model.addAttribute("stateDic", StateDic.stateDic());
        model.addAttribute("time",createTimeSpace);
        model.addAttribute("roleId",draftService.selectRoleId());
        return prefix+"draftCheckLeader";
    }

    /**
     * 已分配稿件
     * @param model
     * @param
     * @return
     */
    @RequestMapping("alloted")
    public String alloted(Model model,Draft allot,
                                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace ,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        Page<Draft> page = new Page<Draft>(pageNo, pageSize);
        IPage<Draft> pageInfo = allotService.draftCheckLeaderIndexTow(page,allot,createTimeSpace);
        model.addAttribute("searchInfo", allot);
        model.addAttribute("roleId",draftService.selectRoleId());
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        model.addAttribute("draftTypes",draftService.setDraftType());//稿件类型回显
        model.addAttribute("draftCheckStatus",draftService.setDraftCheckStatus());//稿件审核状态回显
        model.addAttribute("stateDic", StateDic.stateDic());
        model.addAttribute("time",createTimeSpace);
        return prefix+"alloted";
    }
    /**
     * @Author myr
     * @Description 分配跳转页面
     * @Date 21:24 2019/12/11
     * @param model
     * @param id
     * @return 
     **/
    @GetMapping("allotBefore/{id}")
    public String addBefore(Model model,@PathVariable("id")Long id){
        List<SysUser> checkerList = relationService.allotBefore();
        model.addAttribute("checkerList",checkerList);
        model.addAttribute("draftId",id);
        return prefix+"allotDraft";
    }

    /**
     * @Description 稿件校对组长批量分配稿件给校对人
     * @param model
     * @param ids
     * @Author myr
     * @return
     **/
    @RequestMapping("allotBefore")
    public String allotBefore(Model model,String ids) {
        log.info("allotBefore ids-->{}",ids);
        List<SysUser> checkerList = relationService.allotBefore();
        model.addAttribute("checkerList",checkerList);
        model.addAttribute("ids",ids);
        return  prefix +"allotDraft";
    }

    /**
     * @Description //分配给校对人
     * @param checker
     * @param draftId
     * @Author myr
     * @return
     **/
    @PostMapping("allot")
    @ResponseBody
    public AjaxResult add(String checker, String draftId, String ids,String name){
        name = Utility.getGroupName(name);
        if(groupService.existGroupName(name)){
            return AjaxResult.error("组名【"+name+"】今日已存在！");
        }
        boolean result = ids.isEmpty()?relationService.allot(checker,draftId):relationService.allotDrafts(checker,ids,name);
        return toAjax(result);
    }

    /**
     * @Description //稿件校对组长审核首页
     * @Author myr
     * @return
     **/
    @RequestMapping("checkerIndex")
    public String draftCheckIndex(Model model,Draft draft,
                                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        model.addAttribute("draftTypes",draftService.setDraftType());//稿件类型回显
        model.addAttribute("draftCheckStatus",draftService.setDraftCheckStatus());//稿件审核状态回显
        model.addAttribute("stateDic", StateDic.stateDic());
        Page<Draft> page=new Page<>(pageNo,pageSize);
        IPage<Draft> pageInfo = (IPage<Draft>) draftService.draftCheckIndex(page,draft).get("pageInfo");
        //待校对稿件长度
        int code = -1;
        if (draftService.selectRoleId()== SysRole.Draft_Check_Leader){
            code = StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SUCCESS;
        }else if (draftService.selectRoleId()== SysRole.SEVEN_LEADER){
            code = StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SEVEN_SUCCESS;
        }
        if(draft.getGroupId() == null){
            draft.setGroupId("-1");
        }else{
            int needCheckSize = draftService.getNeedCheckSize(draft.getGroupId(), false, code);
            model.addAttribute("needCheckSize",needCheckSize);
        }
        //组名回显
        List<Draft> drafts = (List<Draft>) draftService.draftCheckIndex(page,draft).get("drafts");

        List<String> groupNames = new ArrayList<String>(drafts.size());
        Map<String,String> groups = new HashMap<>();
        for ( Draft draft1:drafts) {
            if(!groupNames.contains(draft1.getGroupName())){
                groupNames.add(draft1.getGroupName());
                groups.put(draft1.getGroupId(),draft1.getGroupName());
            }
        }


        log.info("组名集合--{}",groups);
        model.addAttribute("groups",groups);
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix + "checkerIndex";
    }

    /**
     * @Description //稿件校对组组长审核通过 / 拒绝
     * @Author myr
     * @return
     **/
    @RequestMapping("checkSuccess")
    public String checkSuccess(Model model,Draft draft,
                                  @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        Page<Draft> page=new Page<>(pageNo,pageSize);
        //下拉框显示登录人组内的稿件组id
        QueryWrapper<Draft> draftQueryWrapper=new QueryWrapper<>();
        draftQueryWrapper.eq("status_code",draft.getStatusCode());
        QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
        List<Long> childrenIdByParentId = pptService.getChildrenIdByParentId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        if (childrenIdByParentId.size() != 0){
            groupQueryWrapper=groupQueryWrapper.in("user_id",childrenIdByParentId);
        }
        List<Group> groupList = groupService.list(groupQueryWrapper);
        List<String> stringList=new ArrayList<>(groupList.size());
        if (!CollectionUtils.isEmpty(groupList)) {
            //获取GroupList的group_id字段
            for (int i = 0; i < groupList.size(); i++) {
                stringList.add(groupList.get(i).getGroupId());
            }
        }
        if (childrenIdByParentId.size() != 0 && !CollectionUtils.isEmpty(stringList)){
            draftQueryWrapper=draftQueryWrapper.in("group_id",stringList);
        }
        if (!ObjectUtils.isEmpty(createTimeSpace)){
            String begin = createTimeSpace.substring(0,19);
            String end = createTimeSpace.substring(22);
            draftQueryWrapper.lambda().between(Draft::getSubmitTime,begin,end);
        }

        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            draftQueryWrapper = draftQueryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            draftQueryWrapper = draftQueryWrapper.like("draft_title",draft.getDraftTitle());
        }

        if(!ObjectUtils.isEmpty(draft.getDraftType()) && draft.getDraftType() >= DraftType.Image_Text) {
            draftQueryWrapper = draftQueryWrapper.like("draft_type",draft.getDraftType());
        }
        if(!ObjectUtils.isEmpty(draft.getIsPass())) {
            draftQueryWrapper = draftQueryWrapper.eq("is_pass", draft.getIsPass());
        }
        draftQueryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        setDraftType(model);
        setDraftCheckStatus(model);
        //组名回显
        Map<String,String> groupIDList = new HashMap<>();
        List<Draft> drafts = draftService.list(draftQueryWrapper);
        for (Draft draft1:drafts) {
            groupIDList.put(draft1.getGroupId(),groupService.getNameByGroupId(draft1.getGroupId()));
        }
        model.addAttribute("groupIDList",groupIDList);
        model.addAttribute("roleId",draftService.selectRoleId());
        model.addAttribute("time",createTimeSpace);
        IPage<Draft> pageInfo = draftService.page(page, draftQueryWrapper);
        model.addAttribute("stateDic", StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"checkSuccess";
    }


    /**
     * @Description //稿件校对组组长---被驳回
     * 主 / 7
     * @Author myr
     * @return
     **/
    @RequestMapping("checkFalse")
    public String checkFalse(Model model,Draft draft,
                               @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,String submitTimeSpace) {
        Page<Draft> page=new Page<>(pageNo,pageSize);
        //下拉框显示登陆人组内的稿件组id
        QueryWrapper<Draft> draftQueryWrapper=new QueryWrapper<>();
        if(draftService.selectRoleId() == SysRole.SEVEN_LEADER){
            draftQueryWrapper.eq("status_code",StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SEVEN_FAILED);
        }else {
            draftQueryWrapper.eq("status_code", StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_FAILED);
        }
        QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
        List<Long> childrenIdByParentId = pptService.getChildrenIdByParentId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        if (childrenIdByParentId.size() != 0){
            groupQueryWrapper=groupQueryWrapper.in("user_id",childrenIdByParentId);
        }
        List<Group> groupList = groupService.list(groupQueryWrapper);
        List<String> stringList=new ArrayList<>(groupList.size());
        if (groupList!=null) {
            //获取GroupList的group_id字段
            for (int i = 0; i < groupList.size(); i++) {
                stringList.add(groupList.get(i).getGroupId());
            }
        }
        if (childrenIdByParentId!=null && !CollectionUtils.isEmpty(stringList)){
            draftQueryWrapper=draftQueryWrapper.in("group_id",stringList);
        }
        if (!ObjectUtils.isEmpty(createTimeSpace)){
            String begin = createTimeSpace.substring(0,19);
            String end = createTimeSpace.substring(22);
            draftQueryWrapper.lambda().between(Draft::getCreateTime,begin,end);
        }
        if(!ObjectUtils.isEmpty(submitTimeSpace)){
            String begin = submitTimeSpace.substring(0,19);
            String end = submitTimeSpace.substring(22);
            draftQueryWrapper.lambda().between(Draft::getSubmitTime,begin,end);
        }
        if(!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            draftQueryWrapper = draftQueryWrapper.like("submit_time",draft.getSubmitTime());
        }
        if(!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            draftQueryWrapper = draftQueryWrapper.like("draft_title",draft.getDraftTitle());
        }

        if(!ObjectUtils.isEmpty(draft.getDraftType()) && draft.getDraftType() >= DraftType.Image_Text) {
            draftQueryWrapper = draftQueryWrapper.like("draft_type",draft.getDraftType());
        }
        draftQueryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        setDraftType(model);
        setDraftCheckStatus(model);
        //组名回显
        Map<String,String> groupIDList = new HashMap<>();
        List<Draft> drafts = draftService.list(draftQueryWrapper);
        for (Draft draft1:drafts) {
            groupIDList.put(draft1.getGroupId(),groupService.getNameByGroupId(draft1.getGroupId()));
        }
        model.addAttribute("groupIDList",groupIDList);
        model.addAttribute("roleId",draftService.selectRoleId());
        model.addAttribute("submitTimeSpace",submitTimeSpace);
        model.addAttribute("time",createTimeSpace);
        IPage<Draft> pageInfo = draftService.page(page, draftQueryWrapper);
        model.addAttribute("stateDic", StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"checkerFalse";
    }

    /**
     * @Description  稿件校对组长抽查批量通过
     *  批量通过工具类
     * @param
     * @return
     **/
    @PostMapping("check")
    @ResponseBody
    public AjaxResult AuViLeadersuccessAll(@RequestBody List<Long> ids) {
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<>();
        Draft draft = new Draft();
        //获取登录role_id
        long roleId = draftService.selectRoleId();
        Integer code = -1;
        if(roleId == SysRole.Draft_Checker){
            code = StatusWriter.STATUS_WRRITE_ARTICLEREADER_SUCCESS; //稿件校对人通过 1005
        }else if(roleId == SysRole.Draft_Check_Leader){
            code = StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SUCCESS; // 稿件校对组长通过 1006
        }else if(roleId == SysRole.SEVEN_PROOFREADER){
            code = StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_SEVEN_SUCCESS;
        }else if(roleId == SysRole.SEVEN_LEADER){
            code = StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SEVEN_SUCCESS;
        }
        draft.setStatusCode(code);

        draft.setLastOperator(pptService.selectIdByUsername(Utility.getCurrentUsername()));
        queryWrapper.in("id", ids);

        draftService.update(draft, queryWrapper);
        for (int i = 0; i < ids.size(); i++) {
            Check check = new Check();
            check.setIsPass(true);
            check.setPreStatusCode(StatusWriter.STATUS_WRRITE_ARTICLEREADER_SUCCESS);
            check.setOverStatusCode(StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SUCCESS);
            check.setCreateTime(LocalDateTime.now());
            check.setUpdateTime(LocalDateTime.now());
            check.setUserId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
            check.setDraftId(draftService.getOne(new QueryWrapper<Draft>().eq("id", ids.get(i))).getId());
            pptService.insertCheck(check);
            //操作日志
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_CHECK_YES)
                    .setActionContent("批量通过").setGroupId(draft.getGroupId()).setDraftId(ids.get(i)));
        }
        return toAjax(true);
    }

    @GetMapping("LeaderfailedBefore/{id}")
    public String LeaderfailedBefore(@PathVariable("id") Long id, Model model) {
        log.info("===========failedBefore=============>{}", id);
        model.addAttribute("id", id);
        return prefix + "AuViLeaderFailedReason";
    }
    @PostMapping("AuViLeaderFailedReason")
    @ResponseBody
    public AjaxResult AuViLeaderFailedReason(Long id, String reason) {
        log.info("=======SectionLeaderFailedReason==========>{}", id);
        log.info("========================>{}", reason);
        QueryWrapper<Draft> queryWrapper = new QueryWrapper<>();
        Draft draft = new Draft();
        draft.setStatusCode(StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_FAILED);
        draft.setLastOperator(pptService.selectIdByUsername(Utility.getCurrentUsername()));
        queryWrapper.in("id", id);
        draftService.update(draft, queryWrapper);


        Check check = new Check();
        check.setIsPass(false);
        check.setPreStatusCode(StatusWriter.STATUS_WRRITE_ARTICLEREADER_SUCCESS);
        check.setOverStatusCode(StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_FAILED);
        check.setUserId(pptService.getUserByUserName(Utility.getCurrentUsername()).getId());
        check.setDraftId(draftService.getOne(new QueryWrapper<Draft>().eq("id", id)).getId());
        check.setReason(reason);
        pptService.insertCheck(check);
        return toAjax(true);
    }

    /**
     * 稿件类型数据回显
     * @param model
     */
    public void setDraftType(Model model){
        Map<Integer,String> types = new HashMap<Integer,String>();
        types.put(DraftType.Image_Text,"图文");
        types.put(DraftType.QA,"问答");
        types.put(DraftType.PPT,"PPT");
        types.put(DraftType.Audio,"音频");
        types.put(DraftType.SHORT,"短篇微博问答");
        types.put(DraftType.MID,"中篇微博问答");
        types.put(DraftType.LENGHT,"长篇微博问答");
        types.put(DraftType.ACCOUNTS,"公众号文章");
//        types.put(DraftType.SVIDEO,"视频稿件");

        model.addAttribute("draftTypes",types);
    }

    /**
     * 稿件审核状态回显
     * @param model
     */
    public void setDraftCheckStatus(Model model){
        Map<Integer,String> status = new HashMap<Integer,String>();

        status.put(DraftIsPass.Pass,"已通过");
        status.put(DraftIsPass.NotPass,"未通过");
        status.put(DraftIsPass.NotCheck,"未审核");
        model.addAttribute("draftCheckStatus",status);
    }


}
